/**
 * 
 */
package resources;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author pdrabik
 *
 */
public abstract class DataRelays {
	
	private static final Logger log = LoggerFactory.getLogger(DataRelays.class);
	
	private static Map<String,DataGenerator> dataObjs = new HashMap<String, DataGenerator>();
	
//	public static int addDataReader(DataGenerator dg) {
//		dataObjs.put(dg.getInterface().Name(), dg);
//		log.debug("DataInitectors: added "+ dg.getInterface().Name()+" all: "+dataObjs.size());
//		return dataObjs.size();
//	}
	
	public static int addDataReader(String name,DataGenerator dg) {
		int tmp=0;
		for(String s : dataObjs.keySet()) {
			if (s.contains(name)) tmp++;
		}
		String key = name;
		if (tmp>0) key = name+"_"+(tmp-1);
		dataObjs.put(key, dg);
		log.debug("DataInitectors: added "+ key+" all: "+dataObjs.size());
		return dataObjs.size();
	}
	/**
	 * Removes data relay instance identified by name. Stops if neccesary.
	 * @param name Data relay instance
	 * @return Ammount of data relays remaining.
	 */
	public static int dropDataReader(String name) {
		stop(name);
		dataObjs.remove(name);
		return dataObjs.size();
	}
	/**
	 * 
	 * @param dg
	 * @return
	 */
	public static int dropDataReader(DataGenerator dg) {
		dropDataReader(dg.getName());
		return dataObjs.size();
	}
	
	public static void clear() {
		dataObjs.clear();
	}
	
	public static void start(String action) throws Exception {
		dataObjs.get(action).start(action);
	}
	
	public static void stop(String action) {
//		long tmp = 0; TODO dorobic to do SYNCHRO
//		for (DataGenerator dg : dataObjs.values()) {
//			tmp = Math.max(tmp,dg.getCorrelationId());
//		}
//		log.debug("max is : " + tmp);
		dataObjs.get(action).stop();
	}
	
	public static int stopAll() {
		int i=0;
		Collection<DataGenerator> geners = dataObjs.values();
		for (DataGenerator dg : geners) {
			dg.stop();
			i++;
		}
		return i;
	}
	
	public static int startAll() {
		int i=0;
		Collection<DataGenerator> geners = dataObjs.values();
		for (DataGenerator dg : geners) {
			dg.start();
			i++;
		}
		return i;
	}
	
	/**
	 * Return DataGenerator instance identified by its name from all injectors
	 * @param name
	 * @return
	 */
	public static DataGenerator getDataReader(String name) { 
		return dataObjs.get(name);
	}
}
